package com.example.srm.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.srm.auth.service.TUserRoleService;
import com.example.srm.constant.UserRoleConstant;
import com.example.srm.domain.TRole;
import com.example.srm.domain.TUserRole;
import com.example.srm.auth.mapper.TUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Slf4j
public class TUserRoleServiceImpl extends ServiceImpl<TUserRoleMapper, TUserRole>
    implements TUserRoleService {

    @Autowired
    private TUserRoleMapper roleMapper;
    @Autowired
    private TUserRoleService userRoleService;
    @Autowired
    private TUserRoleMapper userRoleMapper;

    @Override
    public List<TRole> getRolesByUserId(String id) {

        return userRoleMapper.getRolesByUserId(id);
    }

    /**
     * 分配成功的情况：第一次分配（分配之前用户没有角色）-->允许存在删除失败、新增成功的情况
     *              分配之前有角色-->必须是 删除、新增均成功的情况
     * 其他情况均失败
     * @param id
     * @param roleIDList
     * @return
     */
    @Override
    @Transactional
    public boolean BatchSave(String id, List<String> roleIDList) {
            //封装id集合为对象集合
            List<TUserRole> userRoleList = roleIDList.stream().map(e -> new TUserRole().setUserId(id).setRoleId(e)).collect(Collectors.toList());
            //删除用户角色关系表相应的数据
            HashMap<String, Object> map = new HashMap<>();
            map.put(UserRoleConstant.userId, id);
            //删除前查询用户的角色集合
            List<TUserRole> userRoleMap = userRoleService.listByMap(map);

            boolean delete = userRoleService.removeByMap(map);
            //新增相关的数据
            boolean saveBatch = userRoleService.saveBatch(userRoleList);
            //删除失败、新增成功
            if (!delete&&saveBatch){
                if (userRoleMap.isEmpty()){
                    return true;
                }
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                log.error("分配角色出现异常");
                return false;
            }else if (delete&&saveBatch){
                return true;
            }

        return false;
    }
}




